using System.IO;
using UnityEngine;
public class DataGame {
	
	public const sbyte LEG = 0;
	public const sbyte BODY = 1;
	public const sbyte HEAD = 2;
	public const sbyte HAT = 3;
	public const sbyte EYE = 4;
	public const sbyte HAIR = 5;
	public const sbyte WING = 6;
	
	public const sbyte IMAGE_X1= 0;
	public const sbyte IMAGE_X2 = 1;
	public const sbyte IMAGE_X3 = 2;
	
	public static sbyte[][] imageMonster;	
	public static sbyte[][][] imgItemMap=new sbyte[3][][];
	public static sbyte[][][] imgItemPart=new sbyte[3][][];
	public static sbyte[][] imgItemSkill;//image of skill

	public static sbyte[] _imageMonster;	
	public static sbyte[][] _imgItemMap;
	public static sbyte[][] _imgItemPart;
	public static sbyte[][] _imgItemSkill;//image of skill
		
	public static sbyte[] allPartInfo;
	public static sbyte[] allInfoSmallImageMap;
	public static sbyte[] allInfoSmallImagePlayer;
	public static sbyte[] allInfoSmallImageSkill;
	public static sbyte[] allTreeInfo;
	public static sbyte[] allSkillInfo;
		
	public static sbyte[][] allBigImgMap;
    public static sbyte[][][] allBigImgPlayer = new sbyte[3][][];
	public static sbyte[][] allBigImgNPC;
	public static sbyte[][] allBigImgSkill;//big image of skill
	public static  DataEffect[] Effects;//list aaa effect
	public static DataFrame []allFrameChars;
	public static DataMap[] ALL_MAP_DATA;

	public static MyVector all_monster=new MyVector();
	public static MyVector smallImageFrame=new MyVector();

	public static bool puttingImage;
	private static long lastTimeUpdate;// thoi gian cuoi cung kiem tra thoi han image

	
	//image of game
	//public static Hashtable[]images = (Hashtable[])new Hashtable[3];
	public static MyHashTable  images = new MyHashTable("images");
	MyVector vtImage ;
	public DataGame(){
        for(int i = 0; i < images.size(); i++)
		{
			string ii = i+"";
			images.put(ii, null);
		}			
    }

    public static byte[] binaryTobyteArray(string Filename)
    {
        byte[] data = null;
        try
        {
            // Open file for reading
            System.IO.FileStream FileStream = new System.IO.FileStream(Filename, System.IO.FileMode.Open, System.IO.FileAccess.Read);

            // attach filestream to binary reader
            System.IO.BinaryReader BinaryReader = new System.IO.BinaryReader(FileStream);

            // get total byte length of the file
            long TotalBytes = new System.IO.FileInfo(Filename).Length;

            // read entire file into buffer
            //data = BinaryReader.ReadByte((System.Int32)TotalBytes);
            data = BinaryReader.ReadBytes((System.SByte)TotalBytes);

            // close file reader
            FileStream.Close();
            FileStream.Dispose();
            BinaryReader.Close();

        }
        catch (System.Exception e)
        {
            // Error
            //Debug.Log("Exception caught in process: {0}", e.ToString());
        }

        return data;
    }
	
//	public static final Texture loadImage(String filename) {
//		
//		Texture img = null;
//        img = DrawJ.loadImage(filename);
//        return img;
//    }
	
	public static Image LoadImage(int id )
	{
		Image image=null;
		if(images.get(id+"")!=null)
		{
			image= (Image) images.get(id+"");
		}
		else// khong ton tai trong hashtable
		{
			try {
                
				if(id<10000){// 10k item map
                    image=Util.loadImage(Main.res+"/smallImage/"+(id));	
						
				}else if(id>=10000&&id<20000){//Part
                    image = Util.loadImage(Main.res + "/smallImage/" + (id));		
                   
				}else if(id>=20000&&id<20500){// image big Player 500 tam

                    image = Util.loadImage(Main.res + "/BigImage/Char/treebig_" + (id-20000));	
                   
				}else if(id>=20500&&id<21000){// img Big Map 500 tam
				}else if(id>=21000&&id<31000){// 10k item skill

                    image = Util.loadImage(Main.res + "/smallImage/" + (id));	
                   
				}else if(id>=31000&&id<31500){// img Big skill 500 tam

                    image = Util.loadImage(Main.res + "/smallImage/" + (id));	
                   	
				}else if(id>=31500&&id<32000){// img Big skill 500 tam		

                    image = Util.loadImage(Main.res + "/smallImage/" + (id));		
				}
				else if(id>=31500&&id<32000){// img Big skill 500 tam		
					
					image = Util.loadImage(Main.res + "/smallImage/" + (id));		
				}
			} catch (System.Exception e) {
				
			}
			//gui thong tin image
			if(image!=null)
			{					
				images.put(id+"", image);
			} 
		}		
		return image;					
	}

//	//remove image khi vuot qua thoi gian cho phep
//	public static void RemoveImage()
//	{
//		new Thread(){// xu ly update
//			
//			public void run() {
//				Thread.currentThread().setName("RemoveImage");
//				while(true){
//					
//					try {
//						Thread.sleep(100);
//					} catch (InterruptedException e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//					}	
//				
//					long timeRemoveImage=(System.currentTimeMillis()-lastTimeUpdate)/60000;
//					//thoi gian 5 phut kiem tra 1 lan de thuc hien remove
//					if(timeRemoveImage>=5)
//					{
//						//đang putting thi sleep 100 millis time
//						while (puttingImage) 
//						{
//							try {
//								Thread.sleep(100);
//							} catch (InterruptedException e) {
//								// TODO Auto-generated catch block
//								e.printStackTrace();
//							}
//						}
//						lastTimeUpdate=System.currentTimeMillis();
//						for(int i=0;i<images.length;i++)//image x1,x2,x3
//						{
//							Enumeration names;
//							names = images[i].keys();
//							synchronized(names) {//trong thoi gian duyet hashtable thi khong duoc xu ly put hay remove
//								
//								   while(names.hasMoreElements()) {//duyet qua tung image
//								        Short id = (Short) names.nextElement();//key
////								    	System.out.println(i+"  remove>>>>>>>>  "+id);
//								        if(images[i].containsKey(id))
//								        {						        	
//								        	long time= (System.currentTimeMillis()-images[i].get(id).timeBegin)/60000;				      
//											//nhung image co thoi gian ton tai vuot qua 5 phut se duoc remove
//									        if(time>=5)//remove nhung image da qua thoi gian 5 phut
//											{
//									        	//System.out.println(i+"  remove>>>>>>>>  "+id+","+images.length);
//									        	images[i].remove(id);
//											}
//								        }			      							        
//								    }
//							}
//						   	
////						     System.out.println(i+" List image "+images[i].keySet());
//						}						
//					}									
//				}
//			}
//		}.start();
//	}

	public static void load(){		
				//RemoveImage();//remove image khong su dung trong thoi gian 5 phut
				BinaryReader dis = null;

				try {
						TextAsset bindata = Resources.Load (Main.res+"/file/tree_Map") as TextAsset;

						Stream s = new MemoryStream (bindata.bytes);
						dis = new BinaryReader (s);
						short totalMap = dis.ReadInt16 ();
						ALL_MAP_DATA = new DataMap[totalMap];
						for (int i=0; i<totalMap; i++) {
								short idMap = dis.ReadInt16 ();
				
								ALL_MAP_DATA [idMap] = new DataMap ();
								ALL_MAP_DATA [idMap].w = dis.ReadInt16 ();
								//Debug.Log("WIDTH map ---> " + ALL_MAP_DATA[idMap].w);
								// Debug.Log("Width ---> " + ALL_MAP_DATA[idMap].w);
								ALL_MAP_DATA [idMap].w /= ScaleGUI.numScale;
								ALL_MAP_DATA [idMap].h = dis.ReadInt16 ();
								// Debug.Log("Height ---> " + ALL_MAP_DATA[idMap].h);
								ALL_MAP_DATA [idMap].h /= ScaleGUI.numScale;
                
								int nBkg = dis.ReadInt16 ();
                
								for (int j=0; j<nBkg; j++) {
										DataItemMap data = new DataItemMap ();
										data.idSmallImage = dis.ReadInt16 ();
										data.x = dis.ReadInt16 ();
										data.x /= ScaleGUI.numScale; 
										data.y = dis.ReadInt16 ();
										data.y /= ScaleGUI.numScale; 
               
										data.flip = System.Convert.ToSByte (dis.ReadInt16 ());
                  
										ALL_MAP_DATA [idMap].allBkgMap.addElement (data);
                   
								}
								int nTree = dis.ReadInt16 ();
								for (int j=0; j<nTree; j++) {
										DataItemMap data = new DataItemMap ();
										data.idSmallImage = dis.ReadInt16 ();
										data.x = dis.ReadInt16 ();
										data.x /= ScaleGUI.numScale;
										data.y = dis.ReadInt16 ();
										data.y /= ScaleGUI.numScale;
										data.flip = System.Convert.ToSByte (dis.ReadInt16 ());
										ALL_MAP_DATA [idMap].allItemInMap.addElement (data);
								}
								int nMonster = dis.ReadInt16 ();
								for (int j=0; j<nMonster; j++) {
										DataMonsterMap data = new DataMonsterMap ();
										data.id = dis.ReadInt16 ();
										data.xDefault = dis.ReadInt16 ();
										data.yDefault = dis.ReadInt16 ();
										ALL_MAP_DATA [idMap].allMonsterInMap.addElement (data);
								}

								int nEffect = dis.ReadInt16 ();

								for (int j=0; j<nEffect; j++) {
										DataEffectMap effectMap = new DataEffectMap ();
										effectMap.id = dis.ReadInt16 ();
										effectMap.x = dis.ReadInt16 ();
										effectMap.x /= ScaleGUI.numScale;
										effectMap.y = dis.ReadInt16 ();
										effectMap.y /= ScaleGUI.numScale;
										effectMap.w = dis.ReadInt16 ();

										effectMap.h = dis.ReadInt16 ();
           
										ALL_MAP_DATA [idMap].allEffect.addElement (effectMap);
								}
						}
						dis.Close ();
						//dis.close();
				} catch (IOException e) {  
						return;  
				}

				try {//thong tin effect
						TextAsset bindata = Resources.Load (Main.res+"/file/tree_Effect") as TextAsset;
						Stream s = new MemoryStream (bindata.bytes);
						dis = new BinaryReader (s);

						int countEffect=dis.ReadInt16();//so luong effect

						Effects = new DataEffect[countEffect];
						for (int i = 0; i < countEffect; i++) {
								DataEffect effect = new DataEffect ();

								effect.w = dis.ReadInt16 ();//chieu rong effect
								effect.h = dis.ReadInt16 ();//chieu dai effect
								int countFrame = dis.ReadInt16 ();//so luong frame

								//thong tin frame
								for (int j = 0; j < countFrame; j++) {
										DataEFrame frame = new DataEFrame ();

										int countListImage = dis.ReadInt16 ();//so luong list image

										for (int k = 0; k < countListImage; k++) {
												DataEImage eImage = new DataEImage ();
												eImage.smallID = dis.ReadInt16 ();//id image
												eImage.dx = dis.ReadInt16 ();
												eImage.dy = dis.ReadInt16 ();

												frame.eImages.addElement (eImage);
										}

										effect.frames.addElement (frame);
								}

								//thong tin sequence
								int countSequence = dis.ReadInt16 ();
								for (int j = 0; j < countSequence; j++) {
										int sequence = dis.ReadInt16 ();

										effect.sequences.addElement (sequence);
								}
								Effects [i] = effect;
						}
						dis.Close ();
				} catch (System.Exception e) {
						//e.printStackTrace();
				}
		}

	public static void LoadChar()
	{		
		BinaryReader dis = null;
		try {	
			TextAsset bindata = Resources.Load (Main.res+"/File/tree_FrameChar") as TextAsset;
			Stream s = new MemoryStream (bindata.bytes);
			dis = new BinaryReader (s);

			int countFrame=dis.ReadInt16();//so luong frame

			allFrameChars= new DataFrame[countFrame];
			for(int i=0;i<countFrame;i++)
			{
				allFrameChars[i]= new DataFrame();
				allFrameChars[i].idFrame=dis.ReadInt16();//id frame
				
				for(int j=0;j<3;j++)//3 huong char
				{
					allFrameChars[i].frameImages[j].removeAllElements();
					int nFrameImage=dis.ReadInt16();//so luong frame image
					for(int k=0;k<nFrameImage;k++)
					{
						DataFrameImage frameImage= new DataFrameImage();
						frameImage.idSmallImage=dis.ReadInt16();
						frameImage.flip=dis.ReadInt16();
                        //frameImage.flip /= ScaleGUI.numScale;
						frameImage.x=dis.ReadInt16();
                        frameImage.x /= ScaleGUI.numScale;
						frameImage.y=dis.ReadInt16();
                        frameImage.y /= ScaleGUI.numScale;
						allFrameChars[i].frameImages[j].addElement(frameImage);
					}
				}
				//System.out.println(i+"frame  "+allFrameChars[i].frameImages[1].size());
			}
			//Debug.Log("allFrameChars  "+allFrameChars.Length);
			dis.Close();
		} catch (System.Exception e) {
			//e.printStackTrace();
		}
		
		try {	

			TextAsset bindata = Resources.Load (Main.res+"/file/tree_SmallImages") as TextAsset;
			Stream s = new MemoryStream (bindata.bytes);
			dis = new BinaryReader (s);
			smallImageFrame.removeAllElements();
			int nSmallImageChar=dis.ReadInt16();

			for(int i=0;i<nSmallImageChar;i++)
			{
				DataSmallImageFrame smallImage= new DataSmallImageFrame();
				smallImage.x=dis.ReadInt16();
                //smallImage.x /= ScaleGUI.numScale;
				smallImage.y=dis.ReadInt16();
                //smallImage.y /= ScaleGUI.numScale;
				smallImage.width=dis.ReadInt16();
                Debug.Log("smallImage.width -- " + smallImage.width);
                //smallImage.width /= ScaleGUI.numScale;
				smallImage.height=dis.ReadInt16();
                Debug.Log("smallImage.width -- " + smallImage.height);
                //smallImage.height /= ScaleGUI.numScale;
				smallImage.bigImage=dis.ReadInt16();
				smallImageFrame.addElement(smallImage);
			}
			Debug.Log("nSmallImageChar  "+smallImageFrame.size());
			dis.Close();
		} catch (System.Exception e) {
			//e.printStackTrace();
		}
		
		try {	
			
			int []a={27,81,4,4};
		 
			TextAsset bindata = Resources.Load (Main.res+"/file/tree_Part_") as TextAsset;
			Stream s = new MemoryStream (bindata.bytes);
			dis = new BinaryReader (s);

			int nSmallImageChar=dis.ReadInt16();

			for(int i=0;i<nSmallImageChar;i++)
			{
				int type=dis.ReadInt16();
				int nimage=a[type];
				for(int j=0;j<nimage;j++)
				{
					int id=dis.ReadInt16();
					for(int k=0;k<24;k++)
					{
						int x=dis.ReadInt16();
						int y=dis.ReadInt16();
					}
				}	
			}
			dis.Close();
		} catch (System.Exception e) {
			//e.printStackTrace();
		}
	}
	public static byte version=1;

}